package com.yenlien.traceyun.breed.service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.yenlien.traceyun.business.interceptor.UserAuthUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.breed.dao.BornDao;
import com.yenlien.traceyun.breed.dao.BreedDao;
import com.yenlien.traceyun.breed.dao.BreedDetailDao;
import com.yenlien.traceyun.breed.entity.Born;
import com.yenlien.traceyun.breed.entity.Breed;
import com.yenlien.traceyun.breed.entity.BreedDetail;
import com.yenlien.traceyun.webase.exception.BusinessException;

@Service
public class BornService {
    @Autowired
    private BornDao bornDao;
    @Autowired
    private BreedDao breedDao;
    @Autowired
    private JdbcTemplate jdbc;
    @Autowired
    private BreedDetailDao breedDetailDao;

    public Page<Born> findByList(final Born born) {
        Pageable pageable = PageRequest.of(born.getPage(), born.getPageSize(), Sort.Direction.DESC, ("createtime"));
        return bornDao.findAll(new Specification<Born>() {
            private static final long serialVersionUID = -1396496630802017658L;

            @Override
            public Predicate toPredicate(Root<Born> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> breedName = root.get("breedName");
                //构造查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                Predicate[] predicateA = new Predicate[list.size()];
                Predicate predicateAnd = cb.and(list.toArray(predicateA));

                if (StringUtils.isNotEmpty(born.getBreedName())) {
                    List<Predicate> list2 = new ArrayList<>();
                    list2.add(cb.like(breedName, "%" + born.getBreedName() + "%"));
                    Predicate[] predicateO = new Predicate[list2.size()];
                    Predicate predicateOr = cb.or(list2.toArray(predicateO));
                    return query.where(predicateAnd, predicateOr).getRestriction();
                } else {
                    return predicateAnd;
                }
            }
        }, pageable);
    }

    @Transactional
    public void save(Born born) {
        //繁殖耳号列表
        List<BreedDetail> breedDetailList = born.getBreedDetailList();
        //新增繁殖
        bornDao.save(born);
        //新增养殖
        Breed breed = new Breed();
        breed.setLastStep("soil");
        breed.setBreedName(born.getBreedName());
        breed.setSeedName(born.getSeedName());
        breed.setBatch(born.getBatch());
        breed.setProductId(born.getProductId());
        breed.setTime(born.getTime());
        breed.setPrincipalId(born.getPrincipalId());
        breed.setPrincipalName(born.getPrincipalName());
        breed.setType(born.getType());
        breed.setBreedBaseId(born.getBreedBaseId());
        breed.setBreedBaseName(born.getBreedBaseName());
        breed.setSoilId(born.getSoilId());
        breed.setSoilName(born.getSoilName());
        breed.setBreedNumber(breedDetailList.size());
        breed.setSurplusNumber(breedDetailList.size());
        breed.setSource("繁殖");
        breedDao.save(breed);
        String companyId = UserAuthUtil.getLoginUser().getCompanyId();
        //=================新增养殖关联关系开始=================
        String sql1 = "insert into t_breed_detail (id,batch,last_step,relevance_id,seed_name,type,code,sex,equipment_id,equipment_name,source,time,is_out,company_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        List<Object[]> batchArgs1 = new ArrayList<Object[]>();
        for (BreedDetail breedDetail : breedDetailList) {
            batchArgs1.add(new Object[]{UUID.randomUUID().toString().replaceAll("-", ""), born.getBatch(), born.getLastStep(), breed.getId(), born.getSeedName(), breedDetail.getType(),
                    breedDetail.getCode(), breedDetail.getSex(), breedDetail.getEquipmentId(), breedDetail.getEquipmentName(), "繁殖", breedDetail.getTime(), 0, companyId});
        }
        jdbc.batchUpdate(sql1, batchArgs1);
        //=================新增养殖关联关系结束=================
        //=================新增繁殖关联关系开始=================
        String sql2 = "insert into t_breed_detail (id,batch,last_step,relevance_id,seed_name,type,code,sex,equipment_id,equipment_name,source,time,is_out,company_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        List<Object[]> batchArgs2 = new ArrayList<Object[]>();
        for (BreedDetail breedDetail : breedDetailList) {
            batchArgs2.add(new Object[]{UUID.randomUUID().toString().replaceAll("-", ""), born.getBatch(), born.getLastStep(), born.getId(), born.getSeedName(), breedDetail.getType(),
                    breedDetail.getCode(), breedDetail.getSex(), breedDetail.getEquipmentId(), breedDetail.getEquipmentName(), "繁殖", breedDetail.getTime(), 0, companyId});
        }
        jdbc.batchUpdate(sql2, batchArgs2);
        //母源耳号列表
        List<BreedDetail> parentDetailList = born.getParentDetailList();
        String sql3 = "insert into t_breed_detail (id,batch,last_step,relevance_id,seed_name,type,code,sex,equipment_id,equipment_name,source,time,is_out,company_id) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        List<Object[]> batchArgs3 = new ArrayList<Object[]>();
        for (BreedDetail breedDetail : parentDetailList) {
            batchArgs3.add(new Object[]{UUID.randomUUID().toString().replaceAll("-", ""), born.getBatch(), born.getLastStep(), born.getId(), born.getSeedName(), breedDetail.getType(),
                    breedDetail.getCode(), breedDetail.getSex(), breedDetail.getEquipmentId(), breedDetail.getEquipmentName(), "母源", breedDetail.getTime(), 0, companyId});
        }
        jdbc.batchUpdate(sql3, batchArgs3);
        //=================新增繁殖关联关系结束=================

    }

    public BreedDetail findByTypeAndCode(JSONObject params) {

        BreedDetail breedDetail = breedDetailDao.findBreedDetail(params.getString("type"), params.getString("code"), "养殖");
        if (breedDetail == null) {
            throw new BusinessException("A0001", "此编码不存在");
        }
        return breedDetail;
    }

    public Born findById(String id) {
        Born born = bornDao.findById(id);
        if (born == null) {
            throw new BusinessException("A0001", "数据有误");
        }
        born.setBreedDetailList(breedDetailDao.findByRelevanceIdAndSource(id, "繁殖"));
        born.setParentDetailList(breedDetailDao.findByRelevanceIdAndSource(id, "母源"));
        return bornDao.findById(id);
    }

    public Object findByTypeAndCodeList(String type, List<String> codeList) {
        return breedDetailDao.findByTypeAndCodeList(type, codeList);
    }
}
